<?php

namespace app\common\model;

use think\Model;
use app\common\model\LihuaOrderActivity;

class LihuaActivity extends Model
{
    // 表名
    protected $table = 'lihua_activity';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    
    public function getStarttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['starttime']) ? $data['starttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getEndtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['endtime']) ? $data['endtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStarttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    //获取当前城市所拥有的促销活动 
    public static function getActivityList($city_id){
        $list = [];
        $map= [
            'city_id'   => $city_id,
            'status'    => 1,
        ];
        $res = self::all(function ($query) use ($map) {
            $now = time();
            $query->where($map)
            ->where("'{$now}' BETWEEN `starttime` AND `endtime`");
        });
        //查询出来的数据过滤一下，如果store_list有值，则判断$store_id是否在store_list包含，如果包含则保留，如果不包含则删除
        if ($res) $list = $res;
        return $list;
    }


    //计算活动和满减优惠
    public static function computingOffers($city_id, $data, $user_id, $use_half_Free = 1, $use_sales_free = 1, $store_id = 0 ){
        $list = [];
        $map= [
            'city_id'   => $city_id,
            'status'    => 1,
        ];
        $list = self::all(function ($query) use ($map) {
            $now = time();
            $query->where($map)
            ->where("'{$now}' BETWEEN `starttime` AND `endtime`");
        });
        $cartGood = $data['goods'];
        $goods_nums = $data['goods_nums'];
        $goods_amount = $data['goods_amount'];
        $goodid_price = $data['goodid_price'];
        //property_exists($goods_amount,'{$now}')

        $containsActGood = [
            'half'              => [], //第二份半价
            'sales'             => [], //促销商品
            'half_free'         => 0, //第二份半价优惠费用
            'sales_free'        => 0, //促销商品优惠会用
            'half_mutex'        => 0, //半价活动是否互斥
            'sales_mutex'       => 0, //半价活动是否互斥
            'enough_reduce'     => 0, //满减优惠金额
            'half_act_id'       => [], //第二份半价活动ID-free以及优惠金额
            'sales_act_id'      => [], //限时促销活动ID-free以及优惠金额
            'half_act_name'     => [], //第二份半价活动ID-name以及名称
            'sales_act_name'    => [], //限时促销活动ID-name以及名称
        ];

        foreach ($list as $k => &$v) {
            $v = $v->toArray();
            if($v['type']==0 && $use_half_Free==1){//第二份半价
                $containsActGood = self::getHalfFree($v, $user_id, $containsActGood, $goods_nums, $goodid_price, $store_id);
            }
            if($v['type']==1 && $use_sales_free == 1){//限时折扣
                $containsActGood = self::getSalesFree($v, $user_id, $containsActGood, $goods_nums, $goodid_price, $store_id);
            }
        }

        return $containsActGood;
    }

    //第二份半价计算
    public static function getHalfFree($v, $user_id, $containsActGood, $goods_nums, $goodid_price, $store_id){
        $a = date('Y-m-d 00:00:00');
        $b = date('Y-m-d 23:59:59');        

        $current_time = time(); // 获取当前时间的时间戳  
        $future_time = strtotime('-12 minutes', $current_time); // 将时间戳转换为15分钟后的时间戳  
        $formatted_time = date('Y-m-d H:i:s', $future_time); // 将时间戳格式化为日期时间字符串  
        $where1 = [
            'activity_id'=> $v['id'], 
            'user_id'=> $user_id, 
            'createtime'=> ['between', [$a,$b]],
            'paystatus'=> 1
        ];
        $where2 = [
            'activity_id'=> $v['id'], 
            'user_id'=> $user_id, 
            'createtime'=> ['between', [$a,$b]],
            'paystatus'=> 0
        ];
        $hasGet1 = LihuaOrderActivity::where($where1)->count();
        $hasGet2 = LihuaOrderActivity::where($where2)->where(['createtime'=> ['>', $formatted_time]])->count();
        
        $hasGet = $hasGet1 + $hasGet2;

        $halfActList = LihuaHalfFree::where(['id'=> $v['act_id']])->find();

        
        if( ($hasGet<$halfActList['day_times'] && $halfActList['day_times']>0) || $halfActList['day_times']==0 ){
            $store_list = explode('|', $halfActList['store_list']);
            $freeprice = 0;
            if(in_array($store_id, $store_list) || $halfActList['store_list']==''){
                $actGood = explode(",", $halfActList['goodlist']);
                foreach ($actGood as $k2 => &$v2) {
                    if(array_key_exists($v2,$goods_nums)){//如果购物车中包含第二份半价商品
                        $containsActGood['half'][] = $v2;
                    }
                }
                $cot = 0;
                $freeprice = 0;
                //计算优惠价格
                if(count($containsActGood['half'])>0){
                    foreach ($containsActGood['half'] as $k3 => &$v3) {
                        if($v3==$halfActList['goodlist']){
                            $num = $goods_nums[$v3];
                            //计算能优惠的次数
                            $cot = floor($num/2);
                            if($cot>$halfActList['order_times']) $cot = $halfActList['order_times'];
                            $halfprice = $goodid_price[$v3]/2;
                            $freeprice = $freeprice + round($halfprice*$cot, 2);
                        }
                    }
                }
            }
            $containsActGood['half_free'] = round($containsActGood['half_free'] + $freeprice, 2);
            $containsActGood['half_mutex'] = $halfActList['mutex'];
            // $containsActGood['half_act_id'] = $v['id'];
            // $containsActGood['half_act_name'] = $v['name'];
            $containsActGood['half_act_id'][] = [$v['id'] => $freeprice];
            $containsActGood['half_act_name'][] = [$v['id'] => $v['name']];

        }
        return $containsActGood;
    }

    //限时折扣计算
    public static function getSalesFree($v, $user_id, $containsActGood, $goods_nums, $goodid_price, $store_id){
        $a = date('Y-m-d 00:00:00');
        $b = date('Y-m-d 23:59:59');

        $current_time = time(); // 获取当前时间的时间戳  
        $future_time = strtotime('-12 minutes', $current_time); // 将时间戳转换为15分钟后的时间戳  
        $formatted_time = date('Y-m-d H:i:s', $future_time); // 将时间戳格式化为日期时间字符串  
        $where1 = [
            'activity_id'=> $v['id'], 
            'user_id'=> $user_id, 
            'createtime'=> ['between', [$a,$b]],
            'paystatus'=> 1
        ];
        $where2 = [
            'activity_id'=> $v['id'], 
            'user_id'=> $user_id, 
            'createtime'=> ['between', [$a,$b]],
            'paystatus'=> 0
        ];
        $hasGet1 = LihuaOrderActivity::where($where1)->count();
        $hasGet2 = LihuaOrderActivity::where($where2)->where(['createtime'=> ['>', $formatted_time]])->count();
        
        $hasGet = $hasGet1 + $hasGet2;

        $salesActList = LihuaSalesFree::where(['id'=> $v['act_id']])->find();

        // $salesActList = $salesActList->toArray();
        if(($hasGet<$salesActList['day_times'] && $salesActList['day_times']>0) || $salesActList['day_times']==0 ){
            $store_list = explode('|', $salesActList['store_list']);
            $freeprice = 0;
            if(in_array($store_id, $store_list) || $salesActList['store_list']==''){
                $actGood = json_decode($salesActList['goodlist'], true);
                foreach ($actGood as $good_id => &$good_price) {
                    if(array_key_exists($good_id,$goods_nums)){//如果购物车中包含第二份半价商品
                        $containsActGood['sales'][] = $good_id;
                    }
                }
                $cot = 0;
                //计算优惠价格
                if(count($containsActGood['sales'])>0){
                    foreach ($containsActGood['sales'] as $k3 => &$v3) {
                        $num = $goods_nums[$v3];
                        //计算能优惠的次数
                        $cot = $num;
                        if($salesActList['order_times']>0){
                            if($cot>$salesActList['order_times']) $cot = $salesActList['order_times'];
                        }
                        $salesprice = $goodid_price[$v3];
                        if(isset($actGood[$v3])){
                            $salesprice = $salesprice - $actGood[$v3];
                            $freeprice = $freeprice + round($salesprice*$cot, 2);
                        }
                    }
                }
            }
            $containsActGood['sales_free'] = round($containsActGood['sales_free'] + $freeprice, 2);
            $containsActGood['sales_mutex'] = $salesActList['mutex'];
            // $containsActGood['sales_act_id'] = $v['id'];
            // $containsActGood['sales_act_name'] = $v['name'];
            $containsActGood['sales_act_id'][] = [$v['id'] => round($freeprice, 2)];    
            $containsActGood['sales_act_name'][] = [$v['id'] => $v['name']];
        }
        return $containsActGood;
    }

}
